package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.dongdongshop.config.AlipayConfig;
import com.dongdongshop.data.HttpResponseEnum;
import com.dongdongshop.data.Result;
import com.dongdongshop.txmessage.SendTXMessage;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.order.TbOrder;
import com.dongdongshop.pojo.order.TbOrderItem;
import com.dongdongshop.pojo.pay.TbPayLog;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.*;
import com.dongdongshop.util.IdWorker;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("order")
public class OrderController {

    private final Logger logger= LoggerFactory.getLogger(OrderController.class);

    @Reference
    private AddressServiceI addressServiceI;
    @Reference
    private OrderServiceI orderServiceI;
    @Reference
    private PayLogServiceI payLogServiceI;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private AlipayConfig alipayConfig;
    @Reference
    private SellerServiceI sellerService;

    @Resource
    private IdWorker idWorker;

    @Reference
    private OrderItemServiceI orderItemService;

    @Resource
    private SendTXMessage sendTXMessage;

    Long id=(long)0;
    String userName="";

    @RequestMapping("getOrderInfo")
    public String getOrderInfo(){
        return "getOrderInfo";
    }

    //付款
    @RequestMapping("insertOrder")
    @ResponseBody
    public Result insertOrder(Long addressId, TbOrder tbOrder){
        try {
            TbUser user=(TbUser) SecurityUtils.getSubject().getPrincipal();
            id=user.getId();
            userName=user.getUsername();
            TbOrder order=addressServiceI.getReceiver(addressId,tbOrder);
            order.setUserId(user.getUsername());
            Map<String,String> map=orderServiceI.addOrder(order);
            //创建pay_log信息
            TbPayLog payLog=new TbPayLog();
            payLog.setCreateTime(new Date());
            payLog.setOutTradeNo(map.get("payOrder"));
            payLog.setTotalFee(new BigDecimal(map.get("totalPrice")));
            payLog.setUserId(user.getUsername());
            payLog.setPayType("1");//支付宝支付
            payLog.setTradeState("1");//未付款
            payLogServiceI.addPay(payLog);
//            发送延迟消息
            sendMessage(map.get("payOrder"));
            return Result.jsonResponse(HttpResponseEnum.OK).setData(map);
        }catch (Exception e){
            logger.error("系统错误", e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }

    }

    //            发送延迟消息
    private void sendMessage(String payOrder) {
        System.out.println("进入方法");
        //建立要发送的消息 发送的内容是byte[]数组要转换
        Message msg = new Message("orderStatus",payOrder.getBytes());
        //延时消息
        msg.setDelayTimeLevel(4);
        try {
            //MessageQueueSelector 消息对列选择器（告诉要选择那个队列）
            rocketMQTemplate.getProducer().send(msg);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param subject    订单名称，必填
     * @param total_amount  付款金额，必填
     * @param body 商品描述，可空
     * @return
     */
    @RequestMapping("goPay")
    @ResponseBody
    public String goPay(String out_trade_no,String subject,String total_amount,String body){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getApp_id(),
                alipayConfig.getMerchant_private_key(), alipayConfig.getFormate(), alipayConfig.getCharset(),
                alipayConfig.getAlipay_public_key(), alipayConfig.getSign_type());

        //创建支付交易的对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置请求参数
        alipayRequest.setReturnUrl(alipayConfig.getReturn_url());
        alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        return result;
    }

    /**
     * 同步回调地址
     * 不能在此方法中修改订单状态为已支付 因为此方法仅仅是从支付宝网站提回来的方法 不能当做校验支付是否成功的逻辑
     * @return
     */
    @RequestMapping("return_url")
    public String return_url(HttpServletRequest request, String out_trade_no, String trade_no, String total_amount, Model model) throws Exception {
        System.out.println(">>>>>>>>>> 进入同步回调 <<<<<<<<<<");
        //获取支付宝GET过来反馈信息
//        Map<String,String> params = new HashMap<String,String>();
//        //通过request获取所有的参数
//        Map<String,String[]> requestParams = request.getParameterMap();
//        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用
////            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//        }
//
//        boolean signVerified = AlipaySignature.rsaCheckV1(params,
//               alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(), alipayConfig.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(true) {
            //商户订单号
            System.out.println("商户订单号："+out_trade_no);
            //支付宝交易号
            System.out.println("支付宝交易号:"+trade_no);
            //付款金额
            System.out.println("付款金额："+total_amount);
            model.addAttribute("out_trade_no",out_trade_no);
            model.addAttribute("trade_no",trade_no);
            model.addAttribute("total_amount",total_amount);
            //编写业务
            return "paysuccess";
        }else {
            model.addAttribute("msg","验签失败");
            return "payfail";
        }
    }

    /**
     * 异步回调地址
     * 在此方法中修改订单为已支付(如果是支付成功) 区分退款使用out_biz_no参数
     * @return
     */
    @RequestMapping("notify_url")
    @ResponseBody
    public String notify_url(String out_trade_no,String trade_no,String total_amount,String trade_status,String gmt_create,String gmt_payment,String out_biz_no,HttpServletRequest request) throws Exception {
        System.out.println(">>>>>>>>>> 进入异步回调 <<<<<<<<<<");
        /* *
         *************************页面功能说明*************************
         * 创建该页面文件时，请留心该页面文件中无任何HTML代码及空格。
         * 该页面不能在本机电脑测试，请到服务器上做测试。请确保外部可以访问该页面。
         * 如果没有收到该页面返回的 success 支付宝会继续回调我们(重试) 但是会有时间间隔 间隔越来越长
         * 建议该页面只做支付成功的业务逻辑处理，退款的处理请以调用退款查询接口的结果为准。
         */

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        //获取所有的参数
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(), alipayConfig.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if(signVerified) {//验证成功
            //校验 订单id 支付金额 商家是否和付款保持一致，避免被人篡改信息
            //商户订单号
            System.out.println("商户订单号："+out_trade_no);
            //支付宝交易号
            System.out.println("支付宝交易号:"+trade_no);
            //交易状态
            System.out.println("交易状态:"+trade_status);
            System.out.println("创建时间"+gmt_create);
            System.out.println("支付时间"+gmt_payment);
            System.out.println("金额"+total_amount);
            if(out_biz_no != null || "".equals(out_biz_no)){
                //System.out.println("退款成功");
                return "success";
            }
            //更新paylog和order中状态；清除redis中母订单；调用积分模块等
            TbPayLog payLog = new TbPayLog();
            payLog.setOutTradeNo(out_trade_no);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            payLog.setCreateTime(simpleDateFormat.parse(gmt_create));
            payLog.setPayTime(simpleDateFormat.parse(gmt_payment));
            payLog.setTransactionId(trade_no);
            payLog.setTradeState("2");//已付款
            if(trade_status.equals("TRADE_FINISHED")){ //交易关闭
                //判断该笔订单是否在商户网站中已经做过处理 保证幂等性
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //此代码块真正告诉我们付款成功
                //判断该笔订单是否在商户网站中已经做过处理 保证幂等性
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //保存到mq中 //增加积分
                List<String> list = Arrays.asList(userName,String.valueOf(id), total_amount);
                 sendTXMessage.txMessage(list,payLog);

                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            //同时将支付交易号更新到order表中多个order数据(同一母订单）。没写增加积分的时候放开
            //orderServiceI.updateAlipayOrderByPayOrder(out_trade_no,trade_no);
           // payLogServiceI.updatePayByOutTradeNo(payLog);

            return "success";

        }else {//验证失败
            return "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }

    }


    @RequestMapping("orderReceive")
    public String orderReceive(){
        return "home-order-receive";
    }


    @RequestMapping("getOrder")
    @ResponseBody
    public Result getOrder(){
        try{
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            List<Cart> cartList = new ArrayList<>();
            List<TbOrder> orderList = orderServiceI.selectOrderByUserId(user.getUsername());
            for (TbOrder order : orderList) {
                Cart cart = new Cart();
                cart.setSellerId(order.getSellerId());
                String sellerName = sellerService.getNameById(order.getSellerId());
                cart.setSellerName(sellerName);
                List<TbOrderItem> orderItemList = orderItemService.selectByOrderId(order.getOrderId());
                for (TbOrderItem orderItem : orderItemList) {
                    orderItem.setIdStr(String.valueOf(orderItem.getId()));
                }
                cart.setOrderItemList(orderItemList);
                cart.setPayOrder(String.valueOf(order.getPayOrder()));
                cartList.add(cart);
            }
            return Result.jsonResponse(HttpResponseEnum.OK).setData(cartList);
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }

    }

    @RequestMapping("toRefund")
    @ResponseBody
    public Result toRefund(String idStr){
        try {
            TbOrderItem orderItem = orderItemService.selectOrderItemById(Long.parseLong(idStr));
            TbOrder order = orderServiceI.selectById(orderItem.getOrderId());
            orderItemService.updateStatusById(Long.parseLong(idStr));
            Map<String,String> map = new HashMap<>();
            map.put("out_trade_no",String.valueOf(order.getPayOrder()));
            map.put("trade_no",order.getAlipayOrder());
            map.put("refund_amount",String.valueOf(orderItem.getTotalFee()));
            map.put("refund_reason","想退款");
            map.put("out_request_no",String.valueOf(idWorker.nextId()));
            return Result.jsonResponse(HttpResponseEnum.OK).setData(map);
        } catch (Exception e) {
            logger.error("操作异常", e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }

    @RequestMapping("refund")
    //  @ResponseBody
    public String refund(String out_trade_no,String trade_no,String refund_amount,String refund_reason,String out_request_no,Model model) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getApp_id(),
                alipayConfig.getMerchant_private_key(), alipayConfig.getFormate(),
                alipayConfig.getCharset(), alipayConfig.getAlipay_public_key(), alipayConfig.getSign_type());

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        //支付宝交易号
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        //退款的原因说明
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        model.addAttribute("refund_amount",refund_amount);
        //输出
        return "payfail1";
    }

}
